const express = require('express');
const router = express.Router();

// 导入工具和中间件
const { success, error, badRequest, notFound, asyncHandler, paginated } = require('../utils/response');
const { optionalAuth, authenticateToken } = require('../utils/auth');

// 导入服务层
const studyService = require('../services/studyService');

/**
 * 获取课程分类
 * GET /courses/categories
 */
router.get('/categories', optionalAuth, asyncHandler(async (req, res) => {
  try {
    const categories = await studyService.getCourseCategories();
    success(res, categories);
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 获取推荐课程
 * GET /courses/recommended
 */
router.get('/recommended', optionalAuth, asyncHandler(async (req, res) => {
  try {
    const courses = await studyService.getRecommendedCourses(req.query);
    success(res, courses);
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 搜索课程
 * GET /courses/search
 */
router.get('/search', optionalAuth, asyncHandler(async (req, res) => {
  try {
    const result = await studyService.searchCourses(req.query);
    paginated(res, result.list, result.total, result.page, result.limit);
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 获取课程详情
 * GET /courses/:id
 */
router.get('/:id', optionalAuth, asyncHandler(async (req, res) => {
  const { id } = req.params;
  
  if (!id || isNaN(parseInt(id))) {
    return badRequest(res, '无效的课程ID');
  }
  
  try {
    const course = await studyService.getCourseDetail(parseInt(id), req.user?.id);
    success(res, course);
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 报名课程
 * POST /courses/:id/enroll
 */
router.post('/:id/enroll', authenticateToken, asyncHandler(async (req, res) => {
  const { id } = req.params;
  
  if (!id || isNaN(parseInt(id))) {
    return badRequest(res, '无效的课程ID');
  }
  
  try {
    const result = await studyService.enrollCourse(req.user.id, parseInt(id));
    success(res, result, '报名成功');
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 更新课程进度
 * PUT /courses/:id/progress
 */
router.put('/:id/progress', authenticateToken, asyncHandler(async (req, res) => {
  const { id } = req.params;
  
  if (!id || isNaN(parseInt(id))) {
    return badRequest(res, '无效的课程ID');
  }
  
  try {
    const result = await studyService.updateCourseProgress(req.user.id, parseInt(id), req.body);
    success(res, result, '进度更新成功');
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

module.exports = router;
